package game.module.init.logic;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import game.entity.PlayingRole;
import game.module.user.bean.PlayerBean;
import game.session.SessionManager;
import lion.netty4.message.GamePlayer;

public class RoomConnectManager {

	private static Logger logger = LoggerFactory.getLogger(RoomConnectManager.class);

	public static boolean cacheNewPlayer(Long roomSessionId, GamePlayer gamePlayer, int playerId) {
		// 保存玩家
		PlayingRole existHero = SessionManager.getInstance().getPlayer(playerId);
		if (existHero != null) {
			logger.warn("还有登录信息！,player_id={},newSessionId={}", playerId, roomSessionId);
			GamePlayer oldGamePlayer = existHero.getGamePlayer();
			// 断线重连
			if (gamePlayer == oldGamePlayer) {
				logger.info("玩家sessionId一致");
				SessionManager.getInstance().visit(roomSessionId);
				return true;
			}
			if (oldGamePlayer != null) {
				if (oldGamePlayer.getChannel() != null) {
					oldGamePlayer.close();
				}
				Long oldSessionId = oldGamePlayer.getSessionId();
				logger.info("remove oldSesssionId={}", oldSessionId);
				if (oldSessionId != null) {
					SessionManager.getInstance().removeLogicHero(oldSessionId);
				}
				oldGamePlayer.saveSessionId(null);
			}
		}
		PlayerBean userBean = new PlayerBean();
		userBean.setId(playerId);
		PlayingRole aHero = new PlayingRole(gamePlayer, userBean);
		SessionManager.getInstance().create(roomSessionId, aHero);
		gamePlayer.saveSessionId(roomSessionId);
		return true;
	}

}
